package com.qingcloud.adminbackend.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Licence工具类
 */
public class LicenceUtil {

    static OkHttpClient okHttpClient = new OkHttpClient();

    /**
     * 通过licence获取任务列表
     */
    public static JSONArray getJobList(String url) {
        JSONObject resultObject = getResult(url);
        if (resultObject == null) {
            return new JSONArray();
        }
        return resultObject.getJSONArray("jobList");
    }

    /**
     * 通过licence功能列表
     */
    public static JSONArray getModuleList(String url) {
        JSONObject resultObject = getResult(url);
        if (resultObject == null) {
            return new JSONArray();
        }
        return resultObject.getJSONArray("moduleList");
    }

    /**
     * 通过licence获取限制的微站数量
     */
    public static Integer getStationNum(String url) {
        JSONObject resultObject = getResult(url);
        if (resultObject == null) {
            return -1;
        }
        return resultObject.getIntValue("stationNum");
    }

    /**
     * 通过licenceIP列表列表
     */
    public static List<String> getIpList(String url) {
        JSONObject resultObject = getResult(url);
        if (resultObject == null) {
            return new ArrayList<>();
        }
        return resultObject.getJSONArray("ipList").toJavaList(String.class);
    }

    /**
     * 通过licence获取权限
     */
    private static JSONObject getResult(String url) {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        try {
            String result = call.execute().body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            int errorCode = jsonObject.getIntValue("erroCode");
            if (errorCode == 2000) {
                return jsonObject.getJSONObject("result");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
